package com.example.nfctagcommons.controllers;

import java.lang.reflect.Type;
import java.util.List;

import android.app.Activity;

import com.example.nfctagcommons.classes.Guard;
import com.example.nfctagcommons.crypto.CryptoManager;
import com.example.nfctagcommons.exceptions.ConnectivityException;
import com.example.nfctagcommons.server.HttpsExecuter;
import com.example.nfctagcommons.server.ServerInfo;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class GuardsController {

	private static final Gson gson = new Gson();

	public static List<Guard> getAllGuards(Activity activity) throws ConnectivityException {
		String completeURL = ServerInfo.SERVER_HOST+ServerInfo.SERVICES_PATH;
		String query = "operation=getAllGuards";
		String response = HttpsExecuter.execute(activity, completeURL, query, true);
		try{
        	Type t = new TypeToken<List<Guard>>(){}.getType();
        	List<Guard> list = gson.fromJson(response, t);
	        return list;
        }catch (Exception x){
        	x.printStackTrace();
        	return null;
        }
	}
	public static Guard login(Activity activity, String deviceId, String userName, String guardPassword) throws ConnectivityException{
		String completeURL = ServerInfo.SERVER_HOST+ServerInfo.SERVICES_PATH;
		guardPassword = CryptoManager.sha1(guardPassword);
		String query = "deviceid="+deviceId+"&operation=login&userName="+userName+"&guardPassword="+guardPassword;
		String response = HttpsExecuter.execute(activity, completeURL, query, true);
		try{
			return gson.fromJson(response, Guard.class);
		}catch (Exception x){
			return null;
		}
	}
	
	public static void logout(Activity activity, String deviceId) throws ConnectivityException{
		String completeURL = ServerInfo.SERVER_HOST+ServerInfo.SERVICES_PATH;
		String query = "deviceid="+deviceId+"&operation=logout";
		HttpsExecuter.execute(activity, completeURL, query, true);
	}
}
